package com.jkc.xh.network;

import android.os.Build;
import android.text.TextUtils;

import com.jkc.xh.manager.UserManager;
import com.jkc.xh.utils.DeviceUtils;
import com.jkc.xh.utils.MD5Util;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * Created by wangjie28 on 2015/11/4.
 */
public class RequestHeaderInterceptor implements Interceptor {
    private String mac;

    private String getMac() {
        if (TextUtils.isEmpty(mac)) {
            mac = DeviceUtils.getMac();
            if (TextUtils.isEmpty(mac)) {
                mac = "unknown";
            }
        }
        return mac;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        String hrand = generateHrand();
        String hsign = MD5Util.MD5("android|" + hrand);
        Request original = chain.request();
        Request.Builder builder = original.newBuilder()
                .header("clienttype", "android")
                .header("clientsysver", "android" + Build.VERSION.SDK_INT)
                // 版本号修改
                .header("ver", "v6.0")
                .header("device", getMac())
                .header("hrand", hrand)
                .header("hsign", hsign);

        if (UserManager.isLogin() && !(com.jkc.xh.network.ApiClient.BASE_URL + "login").equals(original.urlString())) {
            String sid = UserManager.getSid();
            if (!TextUtils.isEmpty(sid)) {
                String reSid = encodeHeadInfo(sid);
                if (!TextUtils.isEmpty(reSid)) {
                    builder.header("Cookie", "PHPSESSID=" + reSid);
                }
            }
        }

        builder.method(original.method(), original.body());
        return chain.proceed(builder.build());
    }

    private String generateHrand() {
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        return time + randomStr();
    }

    private static String randomStr() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    private static String encodeHeadInfo( String headInfo ) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0, length = headInfo.length(); i < length; i++) {
            char c = headInfo.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                stringBuffer.append( String.format ("\\u%04x", (int)c) );
            } else {
                stringBuffer.append(c);
            }
        }
        return stringBuffer.toString();
    }
}
